package redisInit

import (
	"context"
	"fmt"
	"ginchat/utils/systemInit"
	"github.com/redis/go-redis/v9"
)

var re *redis.Client

func Get() *redis.Client{
	return re
}

func init() {
	initRe()
}
// initRe 初始化re
func initRe(){
	redisConfig := systemInit.Get().RedisConfig
	re = redis.NewClient(&redis.Options{
		Addr: redisConfig.Addr,
		Password: redisConfig.Password,
		DB: redisConfig.Db,
		PoolSize: redisConfig.PoolSize,
		MinIdleConns: redisConfig.MinIdleConn,
	})

	// Background返回一个非空的Context。它永远不会被取消，没有值，也没有截止日期。
	// 它通常由main函数、初始化和测试使用，并作为传入请求的顶级上下文
	ctx := context.Background()
	pong, err := re.Ping(ctx).Result()
	if err != nil {
		fmt.Println("redis init...",err)
		return
	}
	fmt.Println("redis init successfully:",pong)
}

const (
	PublishKey = "websocket"
)

//Publish  发布消息到Redis
func FPublish(ctx context.Context,channel string,msg string) error{
	var err error
	fmt.Println("Publish.....",msg)
	err = re.Publish(ctx,channel,msg).Err()
	if err != nil{
		fmt.Println("re.Publish filed:",err)
	}
	return err
}

//Subscribe 接收redis消息
func FSubscribe(ctx context.Context,channel string) (string,error){
    //订阅一个或者多个频道的消息
	sub := re.Subscribe(ctx,channel)
	msg,err := sub.ReceiveMessage(ctx)
	if err != nil{
		fmt.Println("sub.ReceiveMessage failed:",err)
		return "",err
	}
	fmt.Println("Subscribe......",msg.Payload)
	return msg.Payload,err
}
